<?php

/*
  VoIP Wholesale 1.0
  ------------------
  Document   : module_mod_trunks
  Created on : Sep 25, 2011, 1:28:26 PM
  Author     : Milos Jovanovic <miloscode@gmail.com>
  Description:

 */
class Module_mod_trunks extends MY_Model {
    
    function __construct() {
        parent::__construct();

		$this->MODULE->config->load('module_config');	
		$this->MODULE->short_name = $this->MODULE->config->item('short_name');
		$this->MODULE->settings_table = $this->MODULE->config->item('settings_table');	 	
		
		$this->PACKAGE->security->load->library('forms');
		$this->PACKAGE->routing->load->library('trunks/trunk_access');
		
		$this->PACKAGE->routing->load->library('carriers/carriers');
		
		$this->PACKAGE->routing->load->library('codecs/codecs');
		
		$this->APPLICATION->load->library('form_validation');
		$this->PACKAGE->regional->load->model('timezone');
		
		$this->order_by = false;
    }

public function is_family_deletion_allowed($family_id)
{
	$query = $this->db->where('routing_family_id',$family_id)->get('origin_trunks');
	
	if($query->num_rows() == 0)
	{
		$response = "true";
	}
	else
	{
		$response = "<ul>";
		foreach($query->result_array() as $origin_trunk)
		{
			$response .= "<li>".$origin_trunk['short_name'] ."</li>";
		}
		$response .= "</ul>";
	}
	
	return $response;
}	

public function route_origin_trunk($post)
{
	//print_r($post);die();

	$final_table = "relations_origin_termination";
	
	$errors = array();
	$fields = array();
	
	$family_id = $post['family_id'];

	// ########################
	// FAMILY VALIDATION
	// ########################	
	if(!$this->APPLICATION->form_validation->required(@$post['family_id']) || @$post['family_id'] == "none")
	{
		$errors[] = lang('msg_please_choose_family');
		$fields[] = "family";
	}	
	
	$count = $this->PACKAGE->routing->trunks->get_family_trunks($family_id);
	if(count($count) < 1)
	{
		$errors[] = lang('msg_family_empty');
		$fields[] = "family";
	}
		
   /*
	* *****************************************************************************
	* THERE ARE SOME ERRORS IN THE FORM - DO NOT PERFORM DATABASE STORING
	* *****************************************************************************
	*/
	if(count($errors) > 0)
	{
		$errors = implode('</li><li>',$errors);
		$fields = implode('**',$fields);
		
		$html = lang('msg_following_errors_occured') . "<br />";
		$html .= "<ul><li>" . $errors . "</li></ul>";
		
		$response = "false|" .  $html . "|" . $fields;
	}
	elseif(count($errors) == 0)
	{
		$posted_trunks = @$post['family_trunks'];
		$all_family_trunk_ids = $this->PACKAGE->routing->trunks->get_family_trunks($family_id);

		
		// generate trunks array
		// i.e.
		// $trunks[21] = "0";
		// 21 --> termination trunk id
		// 0  --> disallowed
		
		if(@is_array($all_family_trunk_ids))
		{
			foreach($all_family_trunk_ids as $term_trunk)
			{
				if($posted_trunks[$term_trunk['id']] == "1")
				{
					$trunks[$term_trunk['id']] = "1";
				}
				if($posted_trunks[$term_trunk['id']] == "0")
				{
					$trunks[$term_trunk['id']] = "0";
				}
			}
		}
		$insert = array();
		
		// update routing_family_id field value in origin_trunks table
		$txt['routing_family_id'] = $family_id;
		$this->db->where('id',$post['origin_trunk_id'])->update('origin_trunks',$txt);
		
		// remove old linked FAMILY TRUNKS!!!
		$this->db->where('origin_trunk_id',$post['origin_trunk_id'])->where('family_id >',0)->delete($final_table);
				
		// process trunks array for storing - FAMILY TRUNKS!!!
		if(is_array(@$trunks) && count(@$trunks) > 0)	
		{		
		foreach($trunks as $termination_trunk_id => $allowed)
		{
			$termination_trunk = $this->PACKAGE->routing->trunks->get_trunk_as_array_by_id($termination_trunk_id,"termination");
			$carrier = $this->PACKAGE->routing->carriers->get_carrier_as_array_by_id($termination_trunk['carrier_id']);
		
			unset($insert);
			$insert['origin_trunk_id'] = $post['origin_trunk_id'];
			$insert['termination_trunk_id'] = $termination_trunk_id;
			$insert['family_id'] = $family_id;
			$insert['termination_carrier_id'] = $carrier['id'];
			$insert['termination_carrier_username'] = $carrier['username'];
			$insert['termination_carrier_status'] = $carrier['status'];
			$insert['termination_trunk_status'] = $termination_trunk['trunk_status'];
			$insert['allowed'] = $allowed;
			
			if($insert['termination_carrier_status'] == "1" && $insert['termination_trunk_status'] == "1" && $insert['allowed'] == "1")
			{
				$insert['status'] = "1";
			}
			else
			{
				$insert['status'] = "0";
			}
			
			$this->db->insert($final_table,$insert);
		
			//$log[] = $insert;
		}
		}

		// remove old linked EXTRA TRUNKS!!!
		$this->db->where('origin_trunk_id',$post['origin_trunk_id'])->where('family_id',NULL)->delete($final_table);		
		
		// process trunks array for storing - EXTRA TRUNKS!!!
		if(is_array(@$post['trunks']) && count(@$post['trunks']) > 0)
		{			
			foreach($post['trunks'] as $trunk_id)
			{
				$trunk = $this->PACKAGE->routing->trunks->get_trunk_as_array_by_id($trunk_id,"termination");
				$carrier = $this->PACKAGE->routing->carriers->get_carrier_as_array_by_id($trunk['carrier_id']);			
			
				unset($insert);
				$insert['origin_trunk_id'] = $post['origin_trunk_id'];
				$insert['termination_trunk_id'] = $trunk_id;
				$insert['family_id'] = NULL;
				$insert['termination_carrier_id'] = $carrier['id'];
				$insert['termination_carrier_username'] = $carrier['username'];				
				$insert['termination_carrier_status'] = $carrier['status'];
				$insert['termination_trunk_status'] = $termination_trunk['trunk_status'];
				$insert['allowed'] = "1";

				if($insert['termination_carrier_status'] == "1" && $insert['termination_trunk_status'] == "1" && $insert['allowed'] == "1")
				{
					$insert['status'] = "1";
				}
				else
				{
					$insert['status'] = "0";
				}
				
				$this->db->insert($final_table,$insert);
				
				//$log[] = $insert;
			}
		}
		
	//print_r($log);die();
		
	$response = "true|" .  lang('msg_routing_settings_stored_successfully');										
	}	
		
	return $response;
}
	
public function check_family_short_name($short_name)
{
	$short_name = strtoupper($short_name);

	$this->MODULE->mysql_table = "termination_families";

	if(!$this->APPLICATION->form_validation->min_length($short_name,6))
	{
			$response = array(
							"result" => false,
							"text" => lang('msg_short_name_too_short')
							 );		
	}	
	elseif(!$this->APPLICATION->form_validation->alpha_dash($short_name))
	{
			$response = array(
							"result" => false,
							"text" => lang('msg_special_chars_in_short_name')
							 );			
	}
	else
	{
		$query = $this->db->where('short_name',$short_name)->get($this->MODULE->mysql_table);
		
		if($query->num_rows() > 0)
		{
			$response = array(
							"result" => false,
							"text" => lang('msg_short_name_already_taken')
							 );
		}
		else
		{
			$response = array(
							"result" => true,
							"text" => lang('msg_short_name_available')
							 );
		}
	}
	return $response;
}

public function add_new_family($post)	
{
	$mysql_table = "termination_families";
	$relations_table = "relations_families_trunks";
	
	$errors = array();
	$fields = array();

	// ###################
	// SHORT NAME VALIDATION
	// ###################
	if(!$this->APPLICATION->form_validation->required($post['short_name']))
	{
		$errors[] = lang('term_empty') . "&nbsp;" . lang('term_short_name');	
		$fields[] = "family_short_name";		
	}
	if($this->APPLICATION->form_validation->required($post['short_name']))
	{	
		$check = $this->check_family_short_name($post['short_name']);

		if($check['result'] != "true")
		{
			$errors[] = $check['text'];
			$fields[] = "family_short_name";
		}	
	}

   /*
	* *****************************************************************************
	* THERE ARE SOME ERRORS IN THE FORM - DO NOT PERFORM DATABASE STORING
	* *****************************************************************************
	*/
	if(count($errors) > 0)
	{
		$errors = implode('</li><li>',$errors);
		$fields = implode('**',$fields);
		
		$html = lang('msg_following_errors_occured') . "<br />";
		$html .= "<ul><li>" . $errors . "</li></ul>";
		
		$response = "false|" .  $html . "|" . $fields;
	}
	elseif(count($errors) == 0)
	{
		// store general trunk information
		$insert['short_name'] = $post['short_name'];
		$insert['description'] = $post['description'];
		$insert['creation_date'] = $this->PACKAGE->regional->timezone->get_current_date_time("mysql_string");		
		
		// insert trunk into appropriate table		
		$this->db->insert($mysql_table,$insert);

		// get ID of inserted trunk
		$family_id = $this->db->insert_id();		
		
		if(is_array(@$post['trunks']) && count(@$post['trunks']) > 0)
		{			
			foreach($post['trunks'] as $trunk_id)
			{
				unset($insert);
				$insert['trunk_id'] = $trunk_id;
				$insert['family_id'] = $family_id;
				
				$this->db->insert($relations_table,$insert);
			}
		}
	$response = "true|" .  lang('msg_family_added_successfully');										
	}

return $response;
}

public function delete_family($family_id)	
{
	$mysql_table = "termination_families";
	$relations_table = "relations_families_trunks";
	
	$this->db->where('id',$family_id)->delete($mysql_table);
	$this->db->where('family_id',$family_id)->delete($relations_table);
	
	return "true";
}

public function edit_family($post)	
{
	$mysql_table = "termination_families";
	$relations_table = "relations_families_trunks";
	$final_table = "relations_origin_termination";
	
	$errors = array();
	$fields = array();


   /*
	* *****************************************************************************
	* THERE ARE SOME ERRORS IN THE FORM - DO NOT PERFORM DATABASE STORING
	* *****************************************************************************
	*/
	if(count($errors) > 0)
	{
		$errors = implode('</li><li>',$errors);
		$fields = implode('**',$fields);
		
		$html = lang('msg_following_errors_occured') . "<br />";
		$html .= "<ul><li>" . $errors . "</li></ul>";
		
		$response = "false|" .  $html . "|" . $fields;
	}
	elseif(count($errors) == 0)
	{
		// store general trunk information
		// $update['short_name'] = $post['short_name']; -- do not change short name!!! ***
		$update['description'] = $post['description'];
		$update['creation_date'] = $this->PACKAGE->regional->timezone->get_current_date_time("mysql_string");		
		
		// get ID of inserted trunk
		$family_id = $post['family_id'];	
				
		// update trunk into appropriate table		
		$this->db->where('id',$family_id)->update($mysql_table,$update);

		// delete all entries from relations table!
		$this->db->where('family_id',$family_id)->delete($relations_table);
				
		if(is_array(@$post['trunks']) && count(@$post['trunks']) > 0)
		{			
			foreach($post['trunks'] as $trunk_id)
			{
				unset($insert);
				$insert['trunk_id'] = $trunk_id;
				$insert['family_id'] = $family_id;
				
				$this->db->insert($relations_table,$insert);
			}
		}
		
		// get new trunks linked with the family we are editing
		$family_new_trunks = $this->PACKAGE->routing->trunks->get_family_trunks($family_id);	
		
		// convert array of new trunks into array of IDs
		if(is_array(@$family_new_trunks) && count(@$family_new_trunks) > 0)
		{
		foreach($family_new_trunks as $trunk)
		{
			$family_new_ids[$trunk['id']] = $trunk['id'];
		}
		}
		
		// REMOVE ALL FINAL ENTRIES THAT ARE NOT LINKED WITH THIS FAMILY ANYMORE!!!
		// ************************************************************************
		$query = $this->db->where('family_id',$family_id)->get($final_table);
		if($query->num_rows() > 0)
		{
		foreach($query->result_array() as $entry)
		{
			// if removed
			if(!isset($family_new_ids[$entry['termination_trunk_id']]))
			{
				$this->db->where('id',$entry['id'])->delete($final_table);
			
				$log[] = $entry['id'];				
			}
			
			$family_existing_final_ids[$entry['origin_trunk_id']][$entry['id']] = $entry['termination_trunk_id'];
		}
		}
		// ************************************************************************
		
		
		
		// ADD ALL NEW TRUNKS THAT WERE NOT LINKED WITH THIS FAMILY!!!
		// ************************************************************************
		if(is_array(@$family_new_ids) && count(@$family_new_ids) > 0)
		{		
		foreach($family_new_ids as $new_trunk_id)
		{
				if(is_array(@$family_existing_final_ids) && count(@$family_existing_final_ids) > 0)
				{				
				foreach($family_existing_final_ids as $origin_trunk_id => $termination_trunks_array)
				{
					if(!in_array($new_trunk_id,$termination_trunks_array))
					{
						//$addition_assoc[][$origin_trunk_id] = $new_trunk_id;
						
						$termination_trunk = $this->PACKAGE->routing->trunks->get_trunk_as_array_by_id($new_trunk_id,"termination");
						$carrier = $this->PACKAGE->routing->carriers->get_carrier_as_array_by_id($termination_trunk['carrier_id']);
						
						unset($insert);
						
						$insert['origin_trunk_id'] = $origin_trunk_id;
						$insert['termination_trunk_id'] = $new_trunk_id;
						$insert['family_id'] = $family_id;
						$insert['termination_carrier_id'] = $termination_trunk['carrier_id'];
						$insert['termination_carrier_username'] = $carrier['username'];
						$insert['termination_carrier_status'] = $carrier['status'];
						$insert['termination_trunk_status'] = $termination_trunk['trunk_status'];
						$insert['allowed'] = 1;
						
						if($insert['termination_carrier_status'] == "1" && $insert['termination_trunk_status'] == "1" && $insert['allowed'] == "1")
						{	
							$insert['status'] = "1";
						}
						else
						{
							$insert['status'] = "0";
						}
						
						$this->db->insert($final_table,$insert);
						
						$log[] = $insert;
					}
				}
				}
		}
		}
		// ************************************************************************
		
		// FOR EACH ORIGIN TRUNK
		$query = $this->db->where('routing_family_id',$family_id)->get('origin_trunks');
		
		if($query->num_rows() > 0)
		{
		$existing = array();
		foreach($query->result_array() as $origin_trunk)
		{
			$origin_trunk_id = $origin_trunk['id'];
		
			// pronadji unose u final tabeli
			$mysql = $this->db->where('origin_trunk_id',$origin_trunk_id)->where('family_id',$family_id)->get($final_table);
			
			if($mysql->num_rows() > 0)
			{
			foreach($mysql->result_array() as $entry)
			{
				$existing[$entry['termination_trunk_id']] = $entry['termination_trunk_id'];
			}
			}			

			if(is_array(@$family_new_ids) && count(@$family_new_ids) > 0)
			{					
			foreach($family_new_ids as $new_trunk_id)
			{
				if(!in_array($new_trunk_id,$existing))
				{
					$termination_trunk = $this->PACKAGE->routing->trunks->get_trunk_as_array_by_id($new_trunk_id,"termination");
					$carrier = $this->PACKAGE->routing->carriers->get_carrier_as_array_by_id($termination_trunk['carrier_id']);
					
					unset($insert);
				
					$insert['origin_trunk_id'] = $origin_trunk_id;
					$insert['termination_trunk_id'] = $new_trunk_id;
					$insert['family_id'] = $family_id;
					$insert['termination_carrier_id'] = $termination_trunk['carrier_id'];
					$insert['termination_carrier_username'] = $carrier['username'];
					$insert['termination_carrier_status'] = $carrier['status'];
					$insert['termination_trunk_status'] = $termination_trunk['trunk_status'];
					$insert['allowed'] = 1;
					
					$this->db->insert($final_table,$insert);
				
					$log[] = $insert;
				}
			}
			}
		}
		}
		//print_r($log);die();
		
		
	$response = "true|" .  lang('msg_family_added_successfully');										
	}

return $response;
}	
	
public function disable_ip_address($ip_id,$trunk_type)
{
	switch($trunk_type):
	
	 case "origin":
	 
		$mysql_table = "origin_access_params";
	 
	 break;
	 
	 case "termination":
	 
		$mysql_table = "termination_access_params";
	 
	 break;
	
	endswitch;

	$update['status'] = 0;
	$update['closure_date'] = $this->PACKAGE->regional->timezone->get_current_date_time("mysql_string");
	
	$this->db->where('id',$ip_id)->update($mysql_table,$update);
	
	return true;
}	
	
public function check_short_name($short_name, $carrier_id, $mysql_table)
{
	$short_name = strtoupper($short_name);

	$this->MODULE->mysql_table = $mysql_table;

	if(!$this->APPLICATION->form_validation->integer($carrier_id) || $this->APPLICATION->form_validation->less_than($carrier_id,1))
	{
		$response = array(
							"result" => false,
							"text" => lang('msg_choose_carrier_first')
						 );
	}
	elseif(!$this->APPLICATION->form_validation->min_length($short_name,6))
	{
			$response = array(
							"result" => false,
							"text" => lang('msg_short_name_too_short')
							 );		
	}	
	elseif(!$this->APPLICATION->form_validation->alpha_dash($short_name))
	{
			$response = array(
							"result" => false,
							"text" => lang('msg_special_chars_in_short_name')
							 );			
	}
	else
	{
		$query = $this->db->where('short_name',$short_name)->where('carrier_id',$carrier_id)->get($this->MODULE->mysql_table);
		
		if($query->num_rows() > 0)
		{
			$response = array(
							"result" => false,
							"text" => lang('msg_short_name_already_taken')
							 );
		}
		else
		{
			$response = array(
							"result" => true,
							"text" => lang('msg_short_name_available')
							 );
		}
	}
	return $response;
}

public function search_trunks($post,$trunk_type)
{
	if($trunk_type == "origin")
	{
		$mysql_table = "origin_trunks";
	}
	if($trunk_type == "termination")
	{
		$mysql_table = "termination_trunks";
	}


	$query = "SELECT * FROM `{$mysql_table}` WHERE ";

	$sql = array();
	
	// carrier
	if($post['carrier_id'] != "none")
	{
		$sql[] = "`carrier_id` = '".$post['carrier_id']."'";
	}
	// short name
	$short_name = strtoupper($post['short_name']);
	$default_short_name = strtoupper(lang('term_short_name'));
	if(strlen($short_name) > 0 && $short_name != $default_short_name)
	{
		$sql[] = "LEFT(`short_name`,".strlen($short_name).") = '".$short_name."'";
	}
	// status
	if($post['status'] != "none")
	{
		if($post['status'] == "all")
		{
			$sql[] = "(`status` = '0' OR `status` = '1')";
		}
		if($post['status'] == "active")
		{
			$sql[] = "(`status` = '1')";
		}
		if($post['status'] == "inactive")
		{
			$sql[] = "`status` = '0'";
		}		
	}
	// max results
	if(@$post['num_of_results'] != "none" && count($sql) > 0)
	{
		$limit = " LIMIT ".$post['num_of_results'];
	}
	
	// prevent empty filters response
	if(count($sql) > 0){
	
		$sql = $query . implode(" AND ",$sql) . @$limit;
	
		if($this->order_by != false)
		{
			$sql .= " ORDER BY `{$this->order_by['column']}` {$this->order_by['direction']}";
		}
	
		//print $sql;die();

		$query = $this->db->query($sql);
	
		foreach($query->result_array() as $trunk)
		{
			$trunks[] = $trunk;
		}		
	}
	else
	{
		$this->PACKAGE->routing->trunks->order_by = array(
															'column' => 'carrier_id',
															'direction' => 'DESC'
														 );
	
		$trunks = $this->PACKAGE->routing->trunks->get_all_trunks($trunk_type);
	}
	return @$trunks;
	
}	

	
public function search_families($post)
{
	$mysql_table = "termination_families";

	$query = "SELECT * FROM `{$mysql_table}` ";

	$sql = array();
	
	// short name
	$short_name = strtoupper($post['short_name']);
	$default_short_name = strtoupper(lang('term_short_name'));
	if(strlen($short_name) > 0 && $short_name != $default_short_name)
	{
		$sql[] = "WHERE LEFT(`short_name`,".strlen($short_name).") = '".$short_name."'";
	}
	// max results
	if(@$post['num_of_results'] != "none" && count($sql) > 0)
	{
		$limit = " LIMIT ".$post['num_of_results'];
	}
	
	// prevent empty filters response
	if(count($sql) > 0){
	
		$sql = $query . implode(" AND ",$sql) . @$limit;
	
		//print $sql;die();

		$query = $this->db->query($sql);
	
		foreach($query->result_array() as $trunk)
		{
			$families[] = $trunk;
		}		
	}
	else
	{
		$families = $this->PACKAGE->routing->trunks->get_all_families();
	}
	return @$families;
	
}

	
public function add_new_trunk($post,$trunk_type)
{
	if($trunk_type == "origin")
	{
		$mysql_table = "origin_trunks";
		$access_table = "origin_access_params";
	}
	elseif($trunk_type == "termination")
	{
		$mysql_table = "termination_trunks";
		$access_table = "termination_access_params";
	}

	
	$errors = array();
	$fields = array();

	
	// ###################
	// CARRIER VALIDATION
	// ###################
	$carrier_id = $post['carrier_id'];
	
	if(!$this->APPLICATION->form_validation->integer($carrier_id) || $this->APPLICATION->form_validation->less_than($carrier_id,1))
	{
		$errors[] = lang('term_empty') . "&nbsp;" . lang('term_carrier');
		$fields[] = "carrier";
	}
	
	// ###################
	// SHORT NAME VALIDATION
	// ###################
	if(!$this->APPLICATION->form_validation->required($post['short_name']))
	{
		$errors[] = lang('term_empty') . "&nbsp;" . lang('term_short_name');	
		$fields[] = "short_name";		
	}

	if($this->APPLICATION->form_validation->required($post['short_name']))
	{	
		$check = $this->check_short_name($post['short_name'], $carrier_id, $mysql_table);

		if($check['result'] != "true")
		{
			$errors[] = $check['text'];
			$fields[] = "short_name";
		}	
	}

	if(!$this->APPLICATION->form_validation->required(@$post['cli_guaranteed']))
	{
		$errors[] = lang('msg_please_choose_cli_value');
		$fields[] = "cli";
	}	
	

	if(!$this->APPLICATION->form_validation->required(@$post['codecs']) || !is_array(@$post['codecs']))
	{
		$errors[] = lang('msg_you_must_choose_at_least_one_codec');
		$fields[] = "codecs";
	}	
	// ########################
	// ACCESS PARAMS VALIDATION
	// ########################	
	$ip_address_segment_1 = $post['ip_address_segment_1'];
	$ip_address_segment_2 = $post['ip_address_segment_2'];
	$ip_address_segment_3 = $post['ip_address_segment_3'];
	$ip_address_segment_4 = $post['ip_address_segment_4'];
	
	$safety_index = 0;
	
	$pairs = array();
	$duplicates = array();
	$tech_prefixes = array();
	$ip_addresses = array();
	
	foreach($post['parameters'] as $key => $row_no)
	{
		// validate only entered parameters - empty fields are not processed
		if(strlen($post['tech_prefixes'][$key]) > 0 || (strlen($ip_address_segment_1[$key]) > 0 || strlen($ip_address_segment_2[$key]) > 0 || strlen($ip_address_segment_3[$key]) > 0 || strlen($ip_address_segment_4[$key]) > 0))
		{
			$tech_prefix = $post['tech_prefixes'][$key];
	
			$ip_address = $ip_address_segment_1[$key] . "." . $ip_address_segment_2[$key] . "." . $ip_address_segment_3[$key] . "." . $ip_address_segment_4[$key];
		
			$detected_trunk = $this->PACKAGE->routing->trunk_access->get_trunk_by_access_params($tech_prefix,$ip_address,$trunk_type);
			
			// IP address and tech prefix do not pass validation
			if(@!$this->APPLICATION->form_validation->valid_ip($ip_address) || @!$this->APPLICATION->form_validation->integer($tech_prefix))
			{
				$pairs[] = "row_" . $row_no;
			}
			elseif($detected_trunk != false)
			{
				$duplicates[] = "row_" . $row_no;
			}
			// IP address and tech prefix are valid - GENERATE ARRAYS FOR STORING ACCESS PARAMS!!!
			else
			{
				$tech_prefixes[$safety_index] = $tech_prefix;
				$ip_addresses[$safety_index] = $ip_address;
				
				$safety_index ++;
			}
		}
	}

	// some wrong access params entered
	if(count($pairs) > 0)
	{
		$errors[] = lang('msg_wrong_access_params_entered');
		$fields[] = implode("**",$pairs);
	}
	// some access params already exist
	if(count($duplicates) > 0)
	{
		$errors[] = lang('msg_some_access_params_already_exist');
		$fields[] = implode("**",$duplicates);
	}
	
	
	
   /*
	* *****************************************************************************
	* THERE ARE SOME ERRORS IN THE FORM - DO NOT PERFORM DATABASE STORING
	* *****************************************************************************
	*/
	if(count($errors) > 0)
	{
		$errors = implode('</li><li>',$errors);
		$fields = implode('**',$fields);
		
		$html = lang('msg_following_errors_occured') . "<br />";
		$html .= "<ul><li>" . $errors . "</li></ul>";
		
		$response = "false|" .  $html . "|" . $fields;
	}
	elseif(count($errors) == 0)
	{
		$carrier = $this->PACKAGE->routing->carriers->get_carrier_as_array_by_id($carrier_id);
	
		// store general trunk information
		$insert['short_name'] = $post['short_name'];
		$insert['description'] = $post['description'];
		$insert['carrier_id'] = $carrier_id;
		$insert['carrier_username'] = $carrier['username'];
		$insert['carrier_status'] = $carrier['status'];
		$insert['trunk_status'] = 1;
		$insert['cli_guaranteed'] = $post['cli_guaranteed'];

		if($insert['carrier_status'] == "1" && $insert['trunk_status'] == "1")
		{
		$insert['status'] = 1;
		}
		else
		{
		$insert['status'] = 0;
		}
		
		
		// prepare selected codecs array
		foreach($post['codecs'] as $column_name => $value)
		{
			$selected_codecs[] = $column_name;
		}
		
		// get available codecs
		$available_codecs = $this->PACKAGE->routing->codecs->get_all_codecs();
		
		// process every single available codec and see if was selected - important for editing!!!
		foreach($available_codecs as $codec)
		{
			if(in_array($codec['codec_field'],$selected_codecs))
			{
				$insert[$codec['codec_field']] = '1';
			}
			else
			{
				$insert[$codec['codec_field']] = '0';
			}
		}
		
		//print_r($insert);die();
		
		// insert trunk into appropriate table		
		$this->db->insert($mysql_table,$insert);
		

		// get ID of inserted trunk
		$trunk_id = $this->db->insert_id();		
		
		// store access params
		if(count($tech_prefixes) > 0 && count($ip_addresses) > 0)
		{
			// reset array
			unset($insert);
			
			foreach($tech_prefixes as $key => $tech_prefix)
			{
				$insert['tech_prefix'] = $tech_prefix;
				$insert['ip_address'] = $ip_addresses[$key];
				$insert['trunk_id'] = $trunk_id;
				$insert['creation_date'] = $this->PACKAGE->regional->timezone->get_current_date_time("mysql_string");
				$insert['status'] = 1;
				
				$this->db->insert($access_table,$insert);
			}
		}
		
		
	$response = "true|" .  lang('msg_trunk_added_successfully');										
	}	
		
	return $response;
}

public function edit_trunk($post,$trunk_id,$trunk_type)
{
	if($trunk_type == "origin")
	{
		$mysql_table = "origin_trunks";
		$access_table = "origin_access_params";
	}
	elseif($trunk_type == "termination")
	{
		$mysql_table = "termination_trunks";
		$access_table = "termination_access_params";
	}

	
	$errors = array();
	$fields = array();

	
	if(!$this->APPLICATION->form_validation->required(@$post['cli_guaranteed']))
	{
		$errors[] = lang('msg_please_choose_cli_value');
		$fields[] = "cli";
	}	
	

	if(!$this->APPLICATION->form_validation->required(@$post['codecs']) || !is_array(@$post['codecs']))
	{
		$errors[] = lang('msg_you_must_choose_at_least_one_codec');
		$fields[] = "codecs";
	}	
	// ########################
	// ACCESS PARAMS VALIDATION
	// ########################	
	$ip_address_segment_1 = $post['ip_address_segment_1'];
	$ip_address_segment_2 = $post['ip_address_segment_2'];
	$ip_address_segment_3 = $post['ip_address_segment_3'];
	$ip_address_segment_4 = $post['ip_address_segment_4'];
	
	$safety_index = 0;
	
	$pairs = array();
	$duplicates = array();
	$tech_prefixes = array();
	$ip_addresses = array();
	
	foreach($post['parameters'] as $key => $row_no)
	{
		// validate only entered parameters - empty fields are not processed
		if(strlen($post['tech_prefixes'][$key]) > 0 || (strlen($ip_address_segment_1[$key]) > 0 || strlen($ip_address_segment_2[$key]) > 0 || strlen($ip_address_segment_3[$key]) > 0 || strlen($ip_address_segment_4[$key]) > 0))
		{
			$tech_prefix = $post['tech_prefixes'][$key];
	
			$ip_address = $ip_address_segment_1[$key] . "." . $ip_address_segment_2[$key] . "." . $ip_address_segment_3[$key] . "." . $ip_address_segment_4[$key];
		
			$detected_trunk = $this->PACKAGE->routing->trunk_access->get_trunk_by_access_params($tech_prefix,$ip_address,$trunk_type);
			
			// IP address and tech prefix do not pass validation
			if(@!$this->APPLICATION->form_validation->valid_ip($ip_address) || @!$this->APPLICATION->form_validation->integer($tech_prefix))
			{
				$pairs[] = "row_" . $row_no;
			}
			elseif($detected_trunk != false)
			{
				$duplicates[] = "row_" . $row_no;
			}
			// IP address and tech prefix are valid - GENERATE ARRAYS FOR STORING ACCESS PARAMS!!!
			else
			{
				$tech_prefixes[$safety_index] = $tech_prefix;
				$ip_addresses[$safety_index] = $ip_address;
				
				$safety_index ++;
			}
		}
	}

	// some wrong access params entered
	if(count($pairs) > 0)
	{
		$errors[] = lang('msg_wrong_access_params_entered');
		$fields[] = implode("**",$pairs);
	}
	// some access params already exist
	if(count($duplicates) > 0)
	{
		$errors[] = lang('msg_some_access_params_already_exist');
		$fields[] = implode("**",$duplicates);
	}
	
	
	
   /*
	* *****************************************************************************
	* THERE ARE SOME ERRORS IN THE FORM - DO NOT PERFORM DATABASE STORING
	* *****************************************************************************
	*/
	if(count($errors) > 0)
	{
		$errors = implode('</li><li>',$errors);
		$fields = implode('**',$fields);
		
		$html = lang('msg_following_errors_occured') . "<br />";
		$html .= "<ul><li>" . $errors . "</li></ul>";
		
		$response = "false|" .  $html . "|" . $fields;
	}
	elseif(count($errors) == 0)
	{
	
		// store general trunk information
		$update['description'] = $post['description'];
		$update['cli_guaranteed'] = $post['cli_guaranteed'];

		// prepare selected codecs array
		foreach($post['codecs'] as $column_name => $value)
		{
			$selected_codecs[] = $column_name;
		}
		
		// get available codecs
		$available_codecs = $this->PACKAGE->routing->codecs->get_all_codecs();
		
		// process every single available codec and see if was selected - important for editing!!!
		foreach($available_codecs as $codec)
		{
			if(in_array($codec['codec_field'],$selected_codecs))
			{
				$update[$codec['codec_field']] = '1';
			}
			else
			{
				$update[$codec['codec_field']] = '0';
			}
		}
		
		//print_r($insert);die();
		
		// insert trunk into appropriate table		
		$this->db->where('id',$trunk_id)->update($mysql_table,$update);
		
		//die($post['description']);
		//die($this->db->last_query());

		// store access params
		if(count($tech_prefixes) > 0 && count($ip_addresses) > 0)
		{
			// reset array
			unset($insert);
			
			foreach($tech_prefixes as $key => $tech_prefix)
			{
				$insert['tech_prefix'] = $tech_prefix;
				$insert['ip_address'] = $ip_addresses[$key];
				$insert['trunk_id'] = $trunk_id;
				$insert['creation_date'] = $this->PACKAGE->regional->timezone->get_current_date_time("mysql_string");
				$insert['status'] = 1;
				
				$this->db->insert($access_table,$insert);
			}
		}
		
		
	$response = "true|" .  lang('msg_trunk_updated_successfully');										
	}	
		
	return $response;
}

}
?>
